<template>
  <div class="learning-assistant">
    <div class="assistant-icon" @click="toggleChat">
      <svg v-if="!isChatOpen" width="32" height="32" viewBox="0 0 100 100" class="robot-icon">
        <!-- Antenna -->
        <line x1="50" y1="25" x2="50" y2="15" stroke="white" stroke-width="4" stroke-linecap="round"/>
        <circle cx="50" cy="12" r="5" fill="white" class="antenna-dot"/>
        <!-- Head -->
        <rect x="30" y="25" width="40" height="30" rx="5" fill="white"/>
        <!-- Eyes -->
        <circle cx="42" cy="40" r="4" fill="#0288d1" class="eye"/>
        <circle cx="58" cy="40" r="4" fill="#0288d1" class="eye"/>
        <!-- Body -->
        <rect x="20" y="55" width="60" height="35" rx="5" fill="white"/>
      </svg>
      <span v-else class="close-icon">×</span>
    </div>
    <div v-if="isChatOpen" class="chat-window">
      <div class="chat-header">
        <span>Zane AI</span>
        <button @click="toggleChat">X</button>
      </div>
      <div class="chat-body" ref="chatBody">
        <div v-for="(message, index) in messages" :key="index" class="message" :class="message.sender">
          <p v-html="message.text"></p>
        </div>
      </div>
      <div class="chat-footer">
        <input type="text" v-model="userInput" @keyup.enter="sendMessage" placeholder="请输入您的问题..." :disabled="isLoading" />
        <button @click="sendMessage">发送</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue';
import { getChatStream } from '@/api/chat';
import { marked } from 'marked';

const isChatOpen = ref(false);
const userInput = ref('');
const messages = ref([
  { text: '你好！我是您的学习助手Zane，有什么可以帮助您的吗？', sender: 'assistant' }
]);
const isLoading = ref(false);
const chatBody = ref(null);

const scrollToBottom = () => {
  if (chatBody.value) {
    chatBody.value.scrollTop = chatBody.value.scrollHeight;
  }
};

watch(messages, () => {
  nextTick(() => {
    scrollToBottom();
  });
}, { deep: true });

const toggleChat = () => {
  isChatOpen.value = !isChatOpen.value;
};

const sendMessage = () => {
  if (userInput.value.trim() === '' || isLoading.value) return;

  const userMessage = userInput.value;
  messages.value.push({ text: userMessage, sender: 'user' });
  userInput.value = '';
  isLoading.value = true;

  const assistantMessage = { rawText: '', text: '<span class="blinking-cursor"></span>', sender: 'assistant' };
  messages.value.push(assistantMessage);

  try {
    const eventSource = getChatStream(userMessage);

    eventSource.onmessage = (event) => {
      if (event.data === '[DONE]') {
        eventSource.close();
        isLoading.value = false;
        assistantMessage.text = marked(assistantMessage.rawText);
        return;
      }

      assistantMessage.rawText += event.data;
      assistantMessage.text = marked(assistantMessage.rawText + '<span class="blinking-cursor"></span>');
      
      nextTick(() => {
        scrollToBottom();
      });
    };

    eventSource.onerror = (error) => {
      console.error("EventSource failed:", error);
      eventSource.close();
      isLoading.value = false;
      if (assistantMessage.rawText && assistantMessage.rawText.trim().length > 0) {
        assistantMessage.text = marked(assistantMessage.rawText);
      } else {
        assistantMessage.text = '抱歉，连接出错了。请稍后再试。';
      }
    };
  } catch (error) {
    console.error('Error sending message:', error);
    assistantMessage.text = '抱歉，连接出错了。请稍后再试。';
    isLoading.value = false;
  }
};
</script>

<style scoped>
.learning-assistant {
  position: fixed;
  bottom: 50px;
  right: 50px;
  z-index: 1000;
}

.assistant-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #29b6f6, #0288d1);
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  color: white;
  transition: all 0.3s cubic-bezier(.25,.8,.25,1);
}

.assistant-icon:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.25);
}

.close-icon {
  font-size: 32px;
  line-height: 1;
  font-weight: 300;
}

.chat-window {
  position: absolute;
  bottom: 80px;
  right: 0;
  width: 350px;
  height: 450px;
  background: white;
  border-radius: 15px;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-header {
  padding: 15px;
  background: #4CAF50;
  color: white;
  font-weight: bold;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-header button {
  background: none;
  border: none;
  color: white;
  font-size: 20px;
  cursor: pointer;
}

.chat-body {
  flex-grow: 1;
  padding: 15px;
  overflow-y: auto;
  background: #f7f7f7;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.message {
  padding: 10px 15px;
  border-radius: 20px;
  max-width: 80%;
  word-wrap: break-word;
}

.message.user {
  background-color: #4CAF50;
  color: white;
  align-self: flex-end;
}

.message.assistant {
  background-color: #e4e4e4;
  color: #333;
  align-self: flex-start;
}

.chat-footer {
  padding: 10px;
  display: flex;
  gap: 10px;
  border-top: 1px solid #e0e0e0;
}

.chat-footer input {
  flex-grow: 1;
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 20px;
  outline: none;
}

.chat-footer button {
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 20px;
  cursor: pointer;
  font-weight: bold;
}

.chat-footer input:disabled {
  background-color: #f2f2f2;
}

:deep(.blinking-cursor) {
  display: inline-block;
  width: 3px;
  height: 1em;
  background-color: #333;
  animation: blink 1s step-end infinite;
  vertical-align: text-bottom;
}

@keyframes blink {
  from, to {
    background-color: transparent;
  }
  50% {
    background-color: #333;
  }
}

.robot-icon .eye {
  animation: blink-eye 4s ease-in-out infinite;
  transform-origin: center;
}

.robot-icon .antenna-dot {
  animation: pulse-dot 2s ease-in-out infinite;
  transform-origin: center;
}

@keyframes blink-eye {
  0%, 90%, 100% { transform: scaleY(1); }
  95% { transform: scaleY(0.1); }
}

@keyframes pulse-dot {
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.3);
    opacity: 0.7;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
}
</style> 